<?php

namespace Home\Controller;
use Think\Controller;

/**
*  收件人管理
*/
class RecipientInfoController extends BaseController {

    /**
     * @desc 获取站点下收件人手机号(联系人管理)
     * @author quyang
     * @update 2017-02-17
     */
    public function queryMobileInfoLabel(){

        $param = I('param.');
        if ( empty($param['userId']) ){
            $this->param_error();
        }

        $mobile = new \Home\Model\MobileInfoModel();

        $page = $param['page'] ? $param['page'] : 1;
        $pageNum = $param['pageNum'] ? $param['pageNum'] : 20;

        //查询收件人信息
        $data = $mobile->mobileInfo( $param['userId'] ,$page ,$pageNum , '' , '' , [0,-1] );

        //总数量
        $mobile_data['totalCount'] = $mobile->countMobileInfo( $param['userId'] , '' , '' , [0,-1] );

        //当前页
        $mobile_data['totalPage'] = $page;

        foreach ( $data as $key=>$val )
        {
            $mobile_id[] = $val['fId'];
        }

        //根据收件人id查询标签信息
        $Receive = new \Home\Model\ReceiveLabelModel();
        $arr = $Receive->queryLabel( $mobile_id );

        $sendLabel = $Receive->queryLabel( $mobile_id , 3 );

        //循环插入标签信息
        foreach ( $data as $data_key=>$data_val )
        {
            //默认为空数组
            $data[$data_key]['label'] = [];
            $data[$data_key]['noticeLabel'] = '';

            //插入普通标签
            foreach ( $arr as $arr_key=>$arr_val )
            {
                if ( $data_val['fId'] == $arr_val['f_receive_id'] )
                {
                    $data[$data_key]['label'][] = $arr[$arr_key];
                }
            }

            //插入通知标签
            foreach ( $sendLabel as $sendLabel_key=>$sendLabel_val )
            {
                if ( $data_val['fId'] == $sendLabel_val['f_receive_id'] )
                {
                    $data[$data_key]['noticeLabel'] = $sendLabel[$sendLabel_key]['f_label'];
                }
            }

        }

        $mobile_data['mobileInfo'] = $data;

        $this->output(true,$mobile_data);

    }

    /**
     * @Desc  : 获取站点标签列表
     * @Author：quyang
     * @Param ：stationId 站点id
     * @Time  ：2017/3/21 16:22
     * @Update：2017/4/26
     **/
    public function recipientLabelList()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) )
        {
            $this->param_error();
        }

        $MobileInfo = new \Home\Model\LabelModel();
        $data = $MobileInfo->queryStationLabel( $param['stationId'] );

        //不管结果,  全部输出成功
        $this ->output( true , $data );

//        if ( $data ){
//            $this->output( true , $data );
//        }
//        $this->output( false );

    }

    /**
     * @Desc  : 根据手机号查找收件人详细信息
     * @Author：quyang
     * @Param ：fRecipientMobile 手机号  stationId 站点id
     * @Time  ：2017/3/22 10:03
     * @Update：2017/3/22
     **/
    public function recipientDetail()
    {

        $param = I('param.');

        if ( empty( $param['fRecipientMobile'] ) || empty( $param['stationId'] ) )
        {
            $this->param_error();
        }

        //查找手机号信息
        $Mobile = new \Home\Model\MobileInfoModel();
        $data = $Mobile->queryMobile( $param['stationId'] , $param['fRecipientMobile'] );

        //查找到收件人信息则返回  否者添加收件人信息
        if ( $data )
        {
            $data['label'] = [];
            $data['noticeLabel'] = '';

            //查找标签信息
            $ReceiveLabel = new \Home\Model\ReceiveLabelModel();
            $labelInfo = $ReceiveLabel->queryLabel( $data['fId'] );

            //通知标签
            $sendLabelInfo = $ReceiveLabel->queryLabel( $data['fId'] , 3 );

            $data['label'] = $labelInfo;

            if ( is_array( $sendLabelInfo ) && count( $sendLabelInfo ) > 0 )
            {
                $data['noticeLabel'] = $sendLabelInfo[0]['f_label'];
            }

            $this->output( true , $data );
        }
        else
        {

            if ( !preg_match( '/^[1][34578]\d{9}$/' , $param['fRecipientMobile'] ) )
            {
                $this->auto_error( '手机号不合法' );
            }

            //添加收件人信息
            $add_data =  $Mobile->addMobile( $param['stationId'] , $param['fRecipientMobile'] , $param['fRecipientName'] );

            if ( $add_data )
            {
                //修改redis
                $Redis_update = new \Home\Server\RedisData();
                $Redis_update->setRecipient_OneData( $param['stationId'] , $param['fRecipientMobile'] );

                //查找新增的收件人信息
                $list = $Mobile->queryMobile( $param['stationId'] , $param['fRecipientMobile'] );

                $list['label'] = [];
                $list['noticeLabel'] = '';

                $this->output( true , $list );
            }
        }
        $this->output( false );

    }

    /**
     * @Desc  : 修改联系人信息（添加联系人）
     * @Author：quyang
     * @Param ：fId 收件人id  stationId 站点id  fRecipientMobile 手机号  fRecipientName 收件人  fRecipientPhone 电话  address 地址  status 拉黑状态（0.正常  -1.拉黑）
     * @Time  ：2017/3/22 10:18
     * @Update：2017/3/27
     **/
    public function updateRecipientDetail()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['fRecipientMobile'] ) || empty( $param['fRecipientName'] ) )
        {
            $this->param_error();
        }

        if ( !preg_match( '/^[1][34578]\d{9}$/' , $param['fRecipientMobile'] ) )
        {
            $this->auto_error( '手机号不合法' );
        }

        $Mobile = new \Home\Model\MobileInfoModel();
        if ( !empty( $param['fId'] ) )
        {
            //更新收件人信息
            $data = $Mobile->updateMobile( $param['fId'] , $param['stationId'] , $param['fRecipientMobile'] ,$param['fRecipientName'] , $param['fRecipientPhone'] , $param['address'] );
        }
        else
        {
            //验证手机号是否已存在
            $existence = $Mobile->queryRecipientMobile( $param['stationId'] , $param['fRecipientMobile'] );

            if ( !$existence )
            {
                //添加收件人信息
                $data =  $Mobile->addMobile( $param['stationId'] , $param['fRecipientMobile'] ,$param['fRecipientName'] , $param['fRecipientPhone'] , $param['address'] );
                $param['fId'] = $data;
            }
            else
            {
                //更新收件人信息
                $data = $Mobile->updateMobile( $existence['f_id'] , $param['stationId'] , $param['fRecipientMobile'] ,$param['fRecipientName'] , $param['fRecipientPhone'] , $param['address'] , '0' );
                $param['fId'] = $existence['f_id'];
//                $this->auto_error( '收件人手机号已存在' );
            }

        }

        if ( $data === false )
        {
            $this->output( false );
        }

        //修改redis
        $Redis_update = new \Home\Server\RedisData();
        $Redis_update->setRecipient_OneData( $param['stationId'] , $param['fRecipientMobile'] );

        $this->output( true , $param['fId'] ,'修改成功' );

    }

    /**
     * @Desc  : 加入黑名单（取消）
     * @Author：quyang
     * @Param ：fid收件人id  stationId站点id  status黑名单状态(0.正常 -1.加入黑名单 1.删除)
     * @Time  ：2017/3/24 9:47
     * @Update：2017/3/24
     **/
    public function updateBlacklist()
    {

        $param = I('param.');

        if ( empty( $param['fId'] ) || empty( $param['stationId'] ) || $param['status'] == '' )
        {
            $this->param_error();
        }

        //修改为删除操作前，判断是否已经是删除状态，用于多终端用户的数据同步
        $Mobile = new \Home\Model\MobileInfoModel();
        if ( $param['status'] == 1)
        {
            $deleteData = $Mobile->queryRecipientMobile( $param['stationId'] , 0 , $param['fId'] );
            if ($deleteData['f_status'] == 1)
            {
                $this -> output(true);
            }
        }


        //更新收件人信息
        $data = $Mobile->updateMobile( $param['fId'] , $param['stationId'] , '' , '' , '' , '' , $param['status'] );

        if ( $data == false )
        {
            $this->output( false );
        }

        //查询收件人手机号
        $mobile_data = $Mobile->queryRecipientMobile( $param['stationId'] , 0 , $param['fId'] );

        if ( is_array( $mobile_data ) && count( $mobile_data ) > 0 )
        {
            //修改redis
            $Redis_update = new \Home\Server\RedisData();
            $Redis_update->setRecipient_OneData( $param['stationId'] , $mobile_data['f_recipient_mobile'] );
        }

        $this->output( true );

    }

    /**
     * @Desc  : 联系人添加自定义标签(接口不能再主从配置下运行)
     * @Author：quyang
     * @Param ：stationId 站点id  label 标签内容  recipientId 收件人id  fId 标签id
     * @Time  ：2017/3/21 17:52
     * @Update：2017/3/21
     **/
    public function addStationLabel_bak()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['label'] ) || empty( $param['recipientId'] ) )
        {
            $this->param_error();
        }

        $Recive = new \Home\Model\ReceiveLabelModel();

        //查询收件人添加的标签数量  不能超过10个标签
        $countLabel = $Recive->countReceiveLabel( $param['stationId'] , $param['recipientId'] );

        if ( $countLabel >=10 )
        {
            $this->auto_error( '收件人标签数量已达上限10个' );
        }

        D()->startTrans();
        //没有标签id则为新建标签
        $Label = new \Home\Model\LabelModel();
        if ( empty( $param['fId'] ) )
        {
            //查询是否已存在标签不存在则新建
            $label_data = $Label->queryLabel( $param['label'] );
            if ( $label_data )
            {
                $param['fId'] = $label_data;
            }
            else
            {
                $param['fId'] = $Label->addLabel( $param['label'] );
            }
        }

        //查询是否已存在标签记录
        $label_status = $Recive->queryLabelExistence( $param['fId'] , $param['stationId'] , $param['recipientId'] );

        $Laber_log = new \Home\Model\StationLabelLogModel();
        if ( $label_status )
        {
            //标签记录存在更新标签状态
            $label_data = $Recive->updateLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] , '0' );
        }
        else
        {
            //添加收件人标签记录
            $recipient_label_data = $Recive->addLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] );

            if ( $recipient_label_data == true )
            {
                //验证站点有没有改标签的添加记录
                $label_info = $Laber_log->queryLabelExistence( $param['fId'] , $param['stationId'] );

                if ( !$label_info )
                {
                    //添加站点标签记录
                    $label_data = $Laber_log->addLabelLog( $param['fId'] , $param['stationId'] );
                }
            }

        }

        if ( $label_data == false && $recipient_label_data == false )
        {
            D()->rollback();
            $this->output( true , $param['fId'] );
        }

        D()->commit();

        //查询收件人手机号
        $Mobile = new \Home\Model\MobileInfoModel();
        $mobile_data = $Mobile->queryRecipientMobile( $param['stationId'] , 0 , $param['recipientId'] );
        if ( is_array( $mobile_data ) && count( $mobile_data ) > 0 )
        {
            //修改redis
            $Redis_update = new \Home\Server\RedisData();
            $Redis_update->setRecipient_OneData($param['stationId'], $mobile_data['f_recipient_mobile']);
        }

        $this->output( true , $param['fId'] );

    }

    /**
     * @Desc  : 联系人添加自定义标签
     * @Author：quyang
     * @Param ：stationId 站点id  label 标签内容  recipientId 收件人id  fId 标签id
     * @Time  ：2017/07/05
     * @Update：2017/07/05
     **/
    public function addStationLabel()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['label'] ) || empty( $param['recipientId'] ) )
        {
            $this->param_error();
        }

        $Recive = new \Home\Model\ReceiveLabelModel();

        //查询收件人添加的标签数量  不能超过10个标签
        $countLabel = $Recive->countReceiveLabel( $param['stationId'] , $param['recipientId'] );

        if ( $countLabel >=10 )
        {
            $this->auto_error( '收件人标签数量已达上限10个' );
        }

        //没有标签id则为新建标签
        $Label = new \Home\Model\LabelModel();
        if ( empty( $param['fId'] ) )
        {
            //查询是否已存在标签不存在则新建
            $label_data = $Label->queryLabel( $param['label'] );
            if ( $label_data )
            {
                $param['fId'] = $label_data;
            }
            else
            {
                $param['fId'] = $Label->addLabel( $param['label'] );
            }
        }

        //查询是否已存在标签记录
        $label_status = $Recive->queryLabelExistence( $param['fId'] , $param['stationId'] , $param['recipientId'] );

        $Laber_log = new \Home\Model\StationLabelLogModel();
        if ( $label_status )
        {
            //标签记录存在更新标签状态
            $label_data = $Recive->updateLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] , '0' );
            //如果更新不成功，将状态设置为 -1 (2017.07.03)
            if ($label_data == false)
            {
                $Recive->updateLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] , '-1' );
                $this->output( true , $param['fId'] ,'添加成功' );
            }
        }
        else
        {
            //添加收件人标签记录
            $recipient_label_data = $Recive->addLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] );

            if ( $recipient_label_data == true )
            {
                //验证站点有没有改标签的添加记录
                $label_info = $Laber_log->queryLabelExistence( $param['fId'] , $param['stationId'] );

                if ( !$label_info )
                {
                    //添加站点标签记录
                    $label_data = $Laber_log->addLabelLog( $param['fId'] , $param['stationId'] );
                    //如果添加站点标签不成功，将标签联系人关系的状态设置为“-1”
                    if ($label_data == false)
                    {
                        $Recive->updateLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] , '-1' );
                        $this->output( true , $param['fId'] ,'添加成功');
                    }
                }
            }
            //如果添加不成功，直接返回值，不做修改
            else
            {
                $this->output( true , $param['fId'] );
            }

        }



        //查询收件人手机号
        $Mobile = new \Home\Model\MobileInfoModel();
        $mobile_data = $Mobile->queryRecipientMobile( $param['stationId'] , 0 , $param['recipientId'] );
        if ( is_array( $mobile_data ) && count( $mobile_data ) > 0 )
        {
            //修改redis
            $Redis_update = new \Home\Server\RedisData();
            $Redis_update->setRecipient_OneData($param['stationId'], $mobile_data['f_recipient_mobile']);
        }

        $this->output( true , $param['fId'] );

    }

    /**
     * @Desc  : 站点删除标签
     * @Author：quyang
     * @Param ：fid 标签id  stationId 站点id  recipientId收件人id
     * @Time  ：2017/3/22 13:47
     * @Update：2017/3/22
     **/
    public function deleteLabel()
    {

        $param = I('param.');

        if ( empty( $param['fId'] ) || empty( $param['stationId'] ) || empty( $param['recipientId'] ) )
        {
            $this->param_error();
        }

        $Recive = new \Home\Model\ReceiveLabelModel();

        //删除联系人标签记录
        $data = $Recive->updateLabelLog( $param['fId'] , $param['stationId'] , $param['recipientId'] , '-1' );

        if ( $data == false )
        {
            $this->output(false);
        }

        //查询收件人手机号
        $Mobile = new \Home\Model\MobileInfoModel();
        $mobile_data = $Mobile->queryRecipientMobile( $param['stationId'] , 0 , $param['recipientId'] );
        if ( is_array( $mobile_data ) && count( $mobile_data ) > 0 )
        {
            //修改redis
            $Redis_update = new \Home\Server\RedisData();
            $Redis_update->setRecipient_OneData($param['stationId'], $mobile_data['f_recipient_mobile']);
        }

        $this->output(true ,array() ,'删除成功');

    }

    /**
     * @Desc  : 根据标签查找收件人信息
     * @Author：quyang
     * @Param ：fid 标签id  stationId 站点id
     * @Time  ：2017/3/22 14:27
     * @Update：2017/3/22
     **/
    public function queryStationLabel()
    {

        $param = I('param.');

        if ( empty( $param['search'] ) || empty( $param['stationId'] ) )
        {
            $this->param_error();
        }

        $mobile = $fId = $name = $fType = '';
        //验证搜索内容
        if(preg_match("/^[1][3,4,5,6,7,8]\d{9}$/", $param['search'])){
            $mobile = $param['search'];
        }
        //根据标签id搜索
        elseif( preg_match("/^\d{1,9}$/", $param['search']) )
        {
            $fId = $param['search'];
        }
        //根据黑名单状态搜索
        elseif( $param['search'] == '-1' )
        {
            $fType = $param['search'];
        }
        //根据姓名搜索
        else
        {
            $name = $param['search'];
        }

        $page = $param['page'] ? $param['page'] : 1;
        $pageNum = $param['pageNum'] ? $param['pageNum'] : 20;

        //当前页
        $mobile_data['totalPage'] = $page;

        //手机号和收件人名称不为空则执行以下代码
        if ( $mobile != '' || $name != '' || $fType != '' )
        {
            $Mobile = new \Home\Model\MobileInfoModel();
            //查询收件人信息
            $data = $Mobile->mobileInfo( $param['stationId'] , $page , $pageNum , $mobile , $name , $fType );

            //总数量
            $mobile_data['totalCount'] = $Mobile->countMobileInfo( $param['stationId'] , $mobile , $name , $fType );
        }

        //标签id不为空则以标签关系表为主表进行查询
        $Receive = new \Home\Model\ReceiveLabelModel();
        if ( $fId != '' )
        {
            $data = $Receive->stationRecipient(  $param['stationId'] , $fId );
            //总数量
            $mobile_data['totalCount'] = $Receive->countStationRecipient( $param['stationId'] , $fId );
        }

        //获取收件人id
        foreach ( $data as $key=>$val )
        {
            $mobile_id[] = $val['fId'];
        }

        //根据收件人id查询标签信息
        $arr = $Receive->queryLabel( $mobile_id );

        //查询通知标签信息
        $sendLabel = $Receive->queryLabel( $mobile_id , 3 );

        //循环插入标签信息
        foreach ( $data as $data_key=>$data_val )
        {
            //赋值为空
            $data[$data_key]['label'] = [];
            $data[$data_key]['noticeLabel'] = '';

            foreach ( $arr as $arr_key=>$arr_val )
            {
                if ( $data_val['fId'] == $arr_val['f_receive_id'] )
                {
                    $data[$data_key]['label'][] = $arr[$arr_key];
                }
            }

            //插入通知标签
            foreach ( $sendLabel as $sendLabel_key=>$sendLabel_val )
            {
                if ( $data_val['fId'] == $sendLabel_val['f_receive_id'] )
                {
                    $data[$data_key]['noticeLabel'] = $sendLabel[$sendLabel_key]['f_label'];
                }
            }
        }

        $mobile_data['mobileInfo'] = $data;

        if ( $data )
        {
            $this->output( true , $mobile_data );
        }

        $this->output( false );

    }

    /**
     * @Desc  : 获取通知方式标签
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/4/26 11:12
     * @Update：2017/4/26
     **/
    public function querySendLabelList()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['mobile'] ) )
        {
            $this->param_error();
        }

        $Mobile = new \Home\Model\MobileInfoModel();
        $Label = new \Home\Model\LabelModel();

        //获取通知标签（1.自定义 2.系统 3.通知标签）
        $label_list = $Label->sendLabelList( 3 );

        //查询收件人通知标签
        $mobileDetailed = $Mobile->querySendLabelList( $param['stationId'] , $param['mobile'] );

        foreach ( $label_list as $key=>$value )
        {

            //默认状态为非默认
            $label_list[$key]['status'] = '0';

            if ( in_array( $value['f_id'] , $mobileDetailed ) )
            {
                $label_list[$key]['status'] = '1';
            }
        }

        $this->output( true , $label_list );

    }

    /**
     * @Desc  : 修改、添加（发送短信微信）标签
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/4/26 13:39
     * @Update：2017/4/26
     **/
    public function updateSendLabel()
    {

        $param = I('param.');

        //站点id   收件人id   标签内容
        if ( empty( $param['stationId'] ) || empty( $param['fId'] ) || empty( $param['label'] ) )
        {
            $this->auto_error();
        }

        $ReceiveLabel = new \Home\Model\ReceiveLabelModel();

        $Label = new \Home\Model\LabelModel();

        //获取通知标签（1.自定义 2.系统 3.通知标签）
        $label_list = $Label->sendLabelList( 3 );

        foreach ( $label_list as $v )
        {

            //获取通知标签id
            if ( $v['f_label'] == $param['label'] )
            {
                $labelId = $v['f_id'];
            }

            $label_id[] = $v['f_id'];
        }

        if ( empty( $labelId ) )
        {
            $this->auto_error( '通知标签不存在' );
        }

        //查询收件人标签是否存在
        $receive_data = $ReceiveLabel->querySendList( $param['stationId'] , $param['fId'] );

        foreach ( $receive_data as $key=>$value )
        {
            //获取通知专用标签是否设置
            if ( in_array( $value['f_receive_label_id'] , $label_id ) )
            {
                $receive_id = $value['f_id'];
            }
        }

        if ( $receive_id )
        {
            //修改
            $receive_status = $ReceiveLabel->updateSendLabel( $receive_id , $labelId );
        }
        else
        {
            //添加
            $receive_status = $ReceiveLabel->addLabelLog( $labelId , $param['stationId'] , $param['fId'] );
        }

        if ( $receive_status )
        {
            $this->output( true );
        }

        $this->output( false );

    }


}
